'use client';

import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import Link from 'next/link';
import { fetchApi } from '@/lib/utils/client';
import { useStudioContext } from '@/app/studio/context';
import { useGoalConfigContext } from '../../context';
import { Separator } from '@/components/ui/separator';
import GoalPreviewPanel from '../../_components/GoalPreviewPanel';
import GoalFormPanel from '../../_components/GoalFormPanel';
import { createEmptyForm, formatInput, parseInput } from '../../types';
import type { FormState } from '../../types';
import type { GoalConfigItem } from '@/types/response/donation/goalConfig';

export default function GoalEditPage()
{
	const router = useRouter();
	const { id } = useParams<{ id: string }>();
	const numericId = parseInt(id);

	const { channelID } = useStudioContext();
	const { items, loading, setSaving } = useGoalConfigContext();

	const [editingItem, setEditingItem] = useState<GoalConfigItem|null>(null);
	const [form, setForm] = useState<FormState>(createEmptyForm());
	const [formInitialized, setFormInitialized] = useState(false);
	const [localSaving, setLocalSaving] = useState(false);

	// ── items 로드 후 form 초기화 ────────────────────
	useEffect(() => {
		if (formInitialized || items.length === 0) {
			return;
		}

		const found = items.find(item => item.id === numericId);
		if (found) {
			setEditingItem(found);
			setForm({
				title: found.title,
				style: found.style,
				startAmount: found.startAmount,
				targetAmount: found.targetAmount,
				startAt: found.startAt ? formatInput(new Date(found.startAt)) : '',
				endAt: found.endAt ? formatInput(new Date(found.endAt)) : '',
				isShowPercent: found.isShowPercent,
				barColor: found.barColor,
				barBackgroundColor: found.barBackgroundColor,
				barHeightPx: found.barHeightPx,
				titleFontFamily: found.titleFontFamily,
				titleFontSizePx: found.titleFontSizePx,
				titleFontColor: found.titleFontColor,
				amountFontFamily: found.amountFontFamily,
				amountFontSizePx: found.amountFontSizePx,
				amountFontColor: found.amountFontColor,
				isActive: found.isActive
			});
			setFormInitialized(true);
		} else if (!loading) {
			alert('목표 설정을 찾을 수 없습니다.');
			router.push('/studio/donation/goal/list');
		}
	}, [items, loading, numericId, formInitialized, router]);

	// ── 폼 필드 변경 ────────────────────────────────
	const handleFormChange = <K extends keyof FormState>(field: K, value: FormState[K]) => {
		setForm(prev => ({ ...prev, [field]: value }));
	};

	// ── 저장 ─────────────────────────────────────────
	const handleSave = async () => {
		if (!channelID || !editingItem) {
			return;
		}

		if (!form.title.trim()) {
			alert('제목을 입력해 주세요.');
			return;
		}
		if (form.targetAmount < 1) {
			alert('목표금액은 1원 이상이어야 합니다.');
			return;
		}

		setLocalSaving(true);
		setSaving(true);

		try {
			await fetchApi('/api/studio/donation/goal/config', {
				method: 'POST',
				body: {
					channelID,
					id: editingItem.id,
					...form,
					startAt: parseInput(form.startAt ?? '') || undefined,
					endAt: parseInput(form.endAt ?? '') || undefined,
					titleFontFamily: form.titleFontFamily || null,
					amountFontFamily: form.amountFontFamily || null
				}
			});

			alert('수정되었습니다.');
		} catch (err) {
			alert(err instanceof Error ? err.message : '저장에 실패했습니다.');
		} finally {
			setLocalSaving(false);
			setSaving(false);
		}
	};

	// ── 취소 ─────────────────────────────────────────
	const handleCancel = () => {
		router.push('/studio/donation/goal/list');
	};

	// ── 로딩 중 ──────────────────────────────────────
	if (!formInitialized) {
		return <div className="goal-config__loading">준비 중...</div>;
	}

	return (
		<>
			<div className="studio-page__title-row">
				<h1 className="studio-page__title">후원 목표 수정</h1>
				<Link href="/studio/donation/goal/list" className="goal-config__btn goal-config__btn--sm">＜ 목록으로</Link>
			</div>
			<div className="pt-5 pb-5">
				<Separator orientation="horizontal" />
			</div>
			<div className="goal-config__layout">
				<GoalPreviewPanel form={form} />

				<Separator orientation="vertical" />

				<GoalFormPanel
					form={form}
					editingItem={editingItem}
					saving={localSaving}
					onFormChange={handleFormChange}
					onSave={handleSave}
					onCancel={handleCancel}
				/>
			</div>
		</>
	);
}